/*
 * This file is part of the SDWebImage package.
 * (c) Olivier Poitrey <rs@dailymotion.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import "UIImageView+WebCache.h"
#import "SDWebImageManager.h"

@implementation UIImageView (WebCache)

- (void)setImageWithURL:(NSURL *)url
{
    [self setImageWithURL:url placeholderImage:nil];
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder
{
    SDWebImageManager *manager = [SDWebImageManager sharedManager];

    // Remove in progress downloader from queue
    [manager cancelForDelegate:self];

    self.image = placeholder;
    
    UIActivityIndicatorView* activityIndicatorView = [[UIActivityIndicatorView alloc] initWithFrame:
                                                      CGRectMake((self.image.size.width - 25.0)/2, 
                                                                 (self.image.size.height - 25.0)/2, 
                                                                 25.0, 
                                                                 25.0)];
	activityIndicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
	activityIndicatorView.tag = 10;
	[activityIndicatorView startAnimating];
	[self addSubview:activityIndicatorView];
    [activityIndicatorView release];
    

    if (url)
    {
        [manager downloadWithURL:url delegate:self];
    }
}

- (void)cancelCurrentImageLoad
{
    [[SDWebImageManager sharedManager] cancelForDelegate:self];
}

- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image
{
    self.image = image;
    
    UIActivityIndicatorView* activityIndicatorView = (UIActivityIndicatorView*)[self viewWithTag:10];
    if (activityIndicatorView.isAnimating)
    {
        [activityIndicatorView stopAnimating];
    }
}

@end
